/*********************************************************
 * File Name   : v4l2-demo.c
 * Author      : Elvis Wang
 * Mail        : huan.wang@ingenic.com
 * Created Time: 2019-12-12 15:37
 ********************************************************/

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/videodev2.h>

/*
 *struct v4l2_capability
 *{
 *        u8 driver[16]; // 驱动名字
 *        u8 card[32]; // 设备名字
 *        u8 bus_info[32]; // 设备在系统中的位置
 *        u32 version; // 驱动版本号
 *        u32 capabilities; // 设备支持的操作
 *        u32 reserved[4]; // 保留字段
 *};
 */

int main()
{
	int fd, ret;
	fd = open("/dev/video1", O_RDWR | O_NONBLOCK, 0);

	struct v4l2_capability cap;
	ret = ioctl (fd, VIDIOC_QUERYCAP, &cap);
	printf("driver: %s\n", cap.driver);
	printf("card: %s\n", cap.card);
	printf("bus_info: %s\n", cap.bus_info);
	printf("version: 0x%08x\n", cap.version);
	printf("capabilities: 0x%08x\n", cap.capabilities);
	printf("reserved: 0x%08x\n", cap.reserved);

	struct v4l2_crop crop;
	struct v4l2_cropcap cropcap;

	sleep(1);
	memset(&cropcap, 0x0, sizeof(cropcap));
	cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	ret = ioctl (fd, VIDIOC_CROPCAP, &cropcap);
	if (ret == 0) {
		printf("cropcap.type: 0x%08x\n", cropcap.type);
		printf("cropcap.bounds.left:   %d\n", cropcap.bounds.left);
		printf("cropcap.bounds.top:    %d\n", cropcap.bounds.top);
		printf("cropcap.bounds.width:  %d\n", cropcap.bounds.width);
		printf("cropcap.bounds.height: %d\n", cropcap.bounds.height);

		printf("cropcap.defrect.left:   %d\n", cropcap.defrect.left);
		printf("cropcap.defrect.top:    %d\n", cropcap.defrect.top);
		printf("cropcap.defrect.width:  %d\n", cropcap.defrect.width);
		printf("cropcap.defrect.height: %d\n", cropcap.defrect.height);

		printf("cropcap.pixelaspect.numerator:   %d\n", cropcap.pixelaspect.numerator);
		printf("cropcap.pixelaspect.denominator: %d\n", cropcap.pixelaspect.denominator);

		memset(&crop, 0x0, sizeof(crop));
		crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		crop.c = cropcap.defrect;
		ret = ioctl (fd, VIDIOC_S_CROP, &cropcap);
	} else {
		printf("/dev/video1 querycap error!\n");
	}


	close(fd);

	return 0;
}
